package com.sina.interfaces.manage.dao.sys;

import com.sina.interfaces.dao.InterFacesDataSourceDao;
import com.sina.interfaces.domain.sys.Permission;
import com.sina.interfaces.domain.sys.Permission_;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import javax.persistence.NoResultException;
import javax.persistence.Tuple;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * 段浩杰   2017-11-03-14:07
 */
@Repository("permissionManageDao")
public class PermissionManageDaoImpl extends InterFacesDataSourceDao implements PermissionManageDao {

    @Override
    public Permission getPermissionByName(String name) {
        String hql = "from Permission where name=:name";
        return unique(hql, new String[]{"name"}, new Object[]{name});
    }


    @Override
    public List<Map<String, Object>> getPermissionList(Permission permission) {
        return template.executeWithNativeSession(session -> {
            // 用于构建标准查询，复合选择，表达式，谓词，排序
            CriteriaBuilder builder = session.getCriteriaBuilder();
            //创建一个CriteriaQuery返回一个元组的对象作为结果。
            CriteriaQuery<Tuple> criteriaQuery = builder.createTupleQuery();
            //所要查询的实体
            Root<Permission> root = criteriaQuery.from(Permission.class);
            //指定要在查询结果中返回的选择项
            criteriaQuery.multiselect(
                    permissionSelection(root)
            );

            Predicate predicate = permissionPredicate(permission, builder, root);
            //指定查询条件
            criteriaQuery.where(predicate);
            //指定用于排序查询结果的排序表达式
            criteriaQuery.orderBy(
                    builder.desc(root.get(Permission_.id))
            );
            //创建查询
            Query<Tuple> query = session.createQuery(criteriaQuery);
            //得到起始条数
            int first = (permission.getPage() - 1) * permission.getRows();

            query.setFirstResult(first);
            query.setMaxResults(permission.getRows());
            //执行查询 query.getResultList()
            return mapWrapperFromTuple(query.getResultList(), HashMap.class);
        });
    }

    @Override
    public Long getPermissionCount(Permission permission) {
        return template.executeWithNativeSession(session -> {
            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
            Root<Permission> root = criteriaQuery.from(Permission.class);
            //根据id查找结果数
            criteriaQuery.select(
                    builder.count(root.get(Permission_.id))
            );
            //组装查询条件
            criteriaQuery.where(
                    permissionPredicate(permission, builder, root)
            );
            //创建插叙语句
            Query<Long> query = session.createQuery(criteriaQuery);
            long count;
            try {
                //得到结果条数
                count = query.getSingleResult();
            } catch (NoResultException e) {
                count = 0;
            }
            return count;
        });
    }

    /**
     * 查询条件组装类
     *
     * @param permission
     * @param builder
     * @param root
     * @return
     */
    protected Predicate permissionPredicate(Permission permission, CriteriaBuilder builder
            , Root<Permission> root) {
        List<Predicate> list = new ArrayList<>(4);

        /*if (permission.getLastId() != null) {
            list.add(
                    builder.lt(root.get(permission_.id), permission.getLastId())
            );
        }*/

        //角色
        if (permission.getName() != null) {
            list.add(
                    builder.like(root.get(Permission_.name), "%" + permission.getName() + "%")
            );
        }

        return builder.and(
                list.toArray(new Predicate[list.size()])
        );
    }


    /**
     * 所要查询的字段组装类
     *
     * @param root
     * @return
     */
    protected List<Selection<?>> permissionSelection(Root<Permission> root) {

        List<Selection<?>> list = new ArrayList<>(12);
        /**
         * 五条一组
         */
        list.add(root.get(Permission_.id).as(Long.class).alias("id"));//id
        list.add(root.get(Permission_.name).alias("name"));//权限名
        list.add(root.get(Permission_.desc).alias("desc"));//权限描述

        return list;
    }


    @Override
    public int deletePermission(Integer id) {
        return template.executeWithNativeSession(session -> {
            String hql = "delete from Permission p where p.id = :id";
            Query query = session.createQuery(hql);
            query.setParameter("id", id);

            return query.executeUpdate();
        });
    }
}
